<?php
/**
 * Created by PhpStorm.
 * User: dream
 * Date: 2018/12/16
 * Time: 19:59
 */

namespace app\admin\controller;

use \think\Db;
use \think\Loader;
use \app\admin\model\User as UserModel;
use \app\admin\model\Product as ProductModel;

class Product extends Main
{
    public $audit = array(
        1 => '未审核',
        2 => '已审核',
        3 => '产品侵权'
    );
    public $source = array(
        1 => '未知',
        2 => '原创',
        3 => '采集'
    );
    public $list_rows = [20, 50, 100, 150, 200];
//    public $list_rows = [1, 2, 3, 4, 5];
    public $repetition = [];//重复产品sku
    public $guids = [];
    public $serial = 0;
    public $company_id;
    public $rate = [];//汇率
    public $platform_contrast = [];//属性对照信息
    public $dir;//跟目录

    public function _initialize()
    {
        parent::_initialize();
        $this->ProductModel = new ProductModel();
        $this->company_id = isession('company_id');
    }


    /**
     * 产品分类列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
        if (checkEntranceList()) {//总公司管理员，跳转选子公司页面
            action('admin/globalFun/choose', ['backtrack' => "index"]);
            return $this->fetch(APP_PATH . request()->module() . '/view/public/choose.html');
        }
        $company_id = iget('company_id') ? iget('company_id') : $this->company_id;
        $where['company_id'] = $company_id;
        $platformStr = sget('platformStr');
        $platformStr && $where['platform'] = $platformStr;

        $lanid = sget('lanid');
        //管理员
        if (checkAdministrator()) {
            $UserModel = new UserModel();
            $user = $UserModel->getUser('', $company_id);
            $user_name = join(',', array_column($user, 'username'));
            $where['user_name'] = ['in', $user_name];
        } else {
            //员工
            $where['user_name'] = ssession('username');
        }

        //分页展示数据
        $data = Db::name('bcategory')
            ->where($where)
            ->order('id desc')
            ->paginate(12, false, ['query' => [
                'platformStr' => $platformStr,
                'company_id' => iget('company_id')
            ]]);
        //分页数据转换数组
        $list = $data->all();
        //获取分类商品数量
        $productNum = [];
        if (checkArr($list)) {
            foreach ($list as $key => $value) {
                $productNum[$value['id']] = $this->ProductModel->productNum($value, $lanid, $company_id);
            }
        }

        //获取语言数据
        $lang = $this->getDictionary('lang');

        $this->assign('productNum', $productNum);
        $this->assign('lang', $lang);
        $this->assign('bcategory', $data);
        return $this->fetch();
    }

    /**
     * 新增分类
     */
    public function addCategory()
    {
        if (post()) {
            $where['platform'] = post('platform');
            $where['bname'] = post('bname');
            $where['user_name'] = ssession('username');
            $where['company_id'] = $this->company_id;
            $res = Db::name('bcategory')
                ->where($where)
                ->find();
            if (checkArr($res)) {
                $this->error('该分类已存在');
            }
            $data = $where;
            $data['truename'] = ssession('truename');
            if (ipost('choose') == 1) {
                $data['zycategory'] = spost('zycategory1');
            } else {
                $data['zycategory'] = spost('zycategory2');
            }
            Db::name('bcategory')
                ->insert($data);
            $this->success('添加成功');
        } else {
            if (checkEntranceAdd()) {
                $this->error("当前状态不允许添加信息");
            }
            //获取智赢分类
            $zy = Db::name('zycategory')->order('id asc')->select();
            $this->assign('zy', $zy);
            //获取平台数据
            $platform = $this->getPlatform();
            return $this->fetch('addCategory', ['platform' => $platform]);
        }
    }

    /**
     * 编辑分类
     * @param $id
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function editCategory($id)
    {
        if (post()) {
            $id = ipost('id');
            $bname = spost('bname');
            $platform = spost('platform');
            if (ipost('choose') == 1) {
                $zycategory = spost('zycategory1');
            } else {
                $zycategory = spost('zycategory2');
            }

            $where['platform'] = $platform;
            $where['bname'] = $bname;
            $where['company_id'] = isession('company_id');
            $where['user_name'] = ssession('username');
            $where['id'] = ['neq', $id];
            $res = DB::name('bcategory')->where($where)->find();
            if (checkArr($res)) {
                $this->error("当前分类已存在");
            }
            $info = DB::name('bcategory')->where('id', $id)->find();
            $updataData['bname'] = $bname;
            $updataData['platform'] = $platform;
            //修改产品主表信息
            $this->ProductModel->updateProductByWhere(['bname' => $info['bname'], 'platform' => $info['platform']], $updataData, '', $this->company_id);
            $updataData['zycategory'] = $zycategory;
            DB::name('bcategory')->where('id', $id)->update($updataData);
            $this->success("更新成功");
        } else {
            //获取智赢分类
            $zy = Db::name('zycategory')->order('id asc')->select();
            $this->assign('zy', $zy);
            $info = DB::name('bcategory')->where('id', $id)->find();
            $this->assign("platform", $this->getPlatform());
            $this->assign("info", $info);
            return $this->fetch('editCategory');
        }
    }

    /**
     * 删除分类
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function delCategory()
    {
        $data = post();
        //获取语言数据
        $langs = $this->getDictionary('lang');
        $company_id = $this->company_id;
        $where['company_id'] = $company_id;
        if (isset($data['ids'])) {//批量删除
            $where['id'] = ['in', join(",", $data['ids'])];
            //获取需要删除的分类信息
            $res = Db::name('bcategory')->where($where)->select();
            foreach ($res as $key => $value) {
                foreach ($langs as $k => $v) {
                    $this->ProductModel->delCategory($value, $v['lanid'], $company_id);
                }
                $this->ProductModel->delCategory($value, '', $company_id);
            }
        } else {//删除个体
            foreach ($langs as $k => $v) {
                $this->ProductModel->delCategory($data, $v['lanid'], $company_id);
            }
            $this->ProductModel->delCategory($data, '', $company_id);
            $where['id'] = $data['id'];
        }
        Db::name('bcategory')->where($where)->delete();
        $this->success('删除成功');
    }

    /**
     * 智赢分类
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function zyCategory()
    {
        $where = '';
        get('name') && $where = "name LIKE '%" . sget('name') . "%'";
        //分页展示数据
        $data = Db::name('zycategory')
            ->where($where)
            ->order('id asc')
            ->paginate(15, false, ['query' => [
                'name' => sget('name')
            ]]);
        $this->assign('zycate', $data);
        return $this->fetch('zyCategory');
    }

    /**
     * 新建智赢分类
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function zyAddCate()
    {
        $name = spost('zyname');
        $where['name'] = $name;
        $res = DB::name('zycategory')->where($where)->find();
        if (checkArr($res)) {
            $this->error("当前分类已存在");
        }
        $insertData['name'] = $name;
        $insertData['timestamp'] = time();
        Db::name('zycategory')->insert($insertData);
        $this->success('添加成功');
    }

    /**
     * 编辑智赢分类名称
     * @param $id
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function zyEditCate($id)
    {
        if (post()) {
            $id = ipost('id');
            $name = spost('name');
            $where['name'] = $name;
            $where['id'] = ['neq', $id];
            $res = DB::name('zycategory')->where($where)->find();
            if (checkArr($res)) {
                $this->error("当前分类已存在");
            }
            DB::name('zycategory')->where('id', $id)->update(['name' => $name]);
            $this->success("更新成功");
        } else {
            $info = DB::name('zycategory')->where('id', $id)->find();
            $this->assign("info", $info);
            return $this->fetch('zyEditCate');
        }
    }

    /**
     * 删除智赢分类
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function zyDelCate()
    {
        $data = post();
        if (checkArr($data['id'])) {
            $where = "id in (" . join(",", $data['id']) . ")";
        } else {
            $where = "id =" . $data['id'];
        }
        Db::name('zycategory')->where($where)->delete();
        $this->success("删除成功");
    }

    /*********************************** 产品 *******************************************/

    /**
     * 采集产品列表
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function productListCollect()
    {
        if (checkEntranceList()) {//总公司管理员，跳转选子公司页面
            action('admin/globalFun/choose', ['backtrack' => "productListCollect"]);
            return $this->fetch(APP_PATH . request()->module() . '/view/public/choose.html');
        }
        $company_id = iget('company_id') ? iget('company_id') : $this->company_id;
        $product = $this->ProductModel->productList(get(), $company_id, ['source' => 3], iget('company_id'));
        $list = $product->all();
        $imgs = [];
        if (checkArr($list)) {
            $guids = array_column($list, 'guid');
            $where['guid'] = ['in', join(',', $guids)];
            $where['lang'] = get('lanid') ? get('lanid') : 'moren';
            $where['serial'] = 0;
            $where['resource_id'] = ['>', 0];
            $imgs = $this->ProductModel->getImgInfo($where, $company_id);
            checkArr($imgs) && $imgs = arrayCombine($imgs, 'guid');
        }
        //获取语言数据
        $lang = $this->getDictionary('lang');
        //获取平台数据
        $platform = $this->getPlatform();

        $this->assign('audits', $this->audit);
        $this->assign('list_rows', $this->list_rows);
        $this->assign('lang', $lang);
        $this->assign('platform', $platform);
        $this->assign('product', $product);
        $this->assign('imgs', $imgs);
        $this->assign('category', $this->getCategory($company_id));
        return $this->fetch('productListCollect');
    }

    /**
     * 自增产品列表
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function productListManual()
    {
        if (checkEntranceList()) {//总公司管理员，跳转选子公司页面
            action('admin/globalFun/choose', ['backtrack' => "productListManual"]);
            return $this->fetch(APP_PATH . request()->module() . '/view/public/choose.html');
        }
        $company_id = iget('company_id') ? iget('company_id') : $this->company_id;
        $product = $this->ProductModel->productList(get(), $company_id, ['source' => 2], iget('company_id'));

        $list = $product->all();
        $imgs = [];
        if (checkArr($list)) {
            $guids = array_column($list, 'guid');
            $where['guid'] = ['in', join(',', $guids)];
            $where['lang'] = get('lanid') ? get('lanid') : 'moren';
            $where['serial'] = 0;
            $where['resource_id'] = ['>', 0];
            $imgs = $this->ProductModel->getImgInfo($where, $company_id);
            checkArr($imgs) && $imgs = arrayCombine($imgs, 'guid');
        }
        //获取语言数据
        $lang = $this->getDictionary('lang');
        //获取平台数据
        $platform = $this->getPlatform();
        $this->assign('list_rows', $this->list_rows);
        $this->assign('audits', $this->audit);
        $this->assign('lang', $lang);
        $this->assign('platform', $platform);
        $this->assign('product', $product);
        $this->assign('imgs', $imgs);
        $this->assign('category', $this->getCategory($company_id));
        return $this->fetch('productListManual');
    }

    /**
     * 产品审核列表
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function productListAudit()
    {
        if (checkEntranceList()) {//总公司管理员，跳转选子公司页面
            action('admin/globalFun/choose', ['backtrack' => "productListAudit"]);
            return $this->fetch(APP_PATH . request()->module() . '/view/public/choose.html');
        }
        $company_id = iget('company_id') ? iget('company_id') : $this->company_id;
        $product = $this->ProductModel->productList(get(), $company_id, ['audit' => 1], iget('company_id'));
        $list = $product->all();
        $imgs = [];
        if (checkArr($list)) {
            $guids = array_column($list, 'guid');
            $where['guid'] = ['in', join(',', $guids)];
            $where['lang'] = get('lanid') ? get('lanid') : 'moren';
            $where['serial'] = 0;
            $where['resource_id'] = ['>', 0];
            $imgs = $this->ProductModel->getImgInfo($where, $company_id);
            checkArr($imgs) && $imgs = arrayCombine($imgs, 'guid');
        }
        //获取语言数据
        $lang = $this->getDictionary('lang');
        //获取平台数据
        $platform = $this->getPlatform();
        $this->assign('list_rows', $this->list_rows);
        $this->assign('lang', $lang);
        $this->assign('platform', $platform);
        $this->assign('product', $product);
        $this->assign('imgs', $imgs);
        return $this->fetch('productListAudit');
    }

    /**
     * 批量转移产品分类
     */
    public function massTransfer()
    {
        $this->ProductModel->massTransfer(post());
        $this->success('转移成功');
    }

    /**
     * 产品新增
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function productAdd()
    {
        if (post()) {
            $data = post();
            $data['lang'] = '';
            //检测SKU获取guid是否重复
            $res = $this->ProductModel->productCheck($data, $this->company_id);
            if ($res['state']) {
                $res = $this->ProductModel->productAdd($data, $this->company_id);
                if ($res) {
                    $this->success('添加成功');
                } else {
                    $this->error('空间内存不足，请提示管理员增加空间容量');
                }
            } else {
                $this->error($res['msg']);
            }
        } else {
            if (checkEntranceAdd()) {
                $this->error("当前状态不允许添加信息");
            }
            //平台变体类名
            $classify = $this->getPlatform();
            if (checkArr($classify)) {
                foreach ($classify as $key => $value) {
                    checkString($value['classify']) && $classify[$key]['classify'] = explode(',', $value['classify']);
                }
            }
            //获取分类数据
            $category = $this->getCategory($this->company_id);
            //获取语言数据
            $lang = $this->getDictionary('lang');
            $this->assign('lang', $lang);
            $this->assign('classify', $classify);
            $this->assign('skucode', guid());
            $this->assign('code', randomkeys(8));
            $this->assign('guid', create_guid());
            return $this->fetch('productAdd', ['category' => $category]);
        }
    }

    /**
     * 获取分类数据
     * @param string $company_id
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getCategory($company_id = '')
    {
        $where['user_name'] = ssession('username');
        $where['company_id'] = $company_id;
        $data = Db::name('bcategory')
            ->where($where)
            ->order('id desc')
            ->select();
        return $data;
    }

    /**
     * 产品编辑
     * @param $id
     * @param $lang
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function productEdit($id, $lang)
    {
        if (post()) {
            if (checkSubmitEdit()) {
                $this->error("当前状态不允许编辑信息");
            }
            $company_id = post('company_id') ? post('company_id') : $this->company_id;
            $res = $this->ProductModel->productEdit(post(), $company_id);
            if ($res['status'] == false) {
                $this->error($res['msg']);
            } else {
                $this->success('编辑成功');
            }
        } else {
            $company_id = iget('company_id') ? iget('company_id') : $this->company_id;
            $productInfo = $this->ProductModel->productInfo($id, $lang, $company_id);
            if (ssession('username') != $productInfo['user_name']) {
                $this->error('当前用户禁止编辑此产品');
            }
            //平台变体类名
            $classify = $this->getPlatform();
            if (checkArr($classify)) {
                foreach ($classify as $key => $value) {
                    checkString($value['classify']) && $classify[$key]['classify'] = explode(',', $value['classify']);
                }
            }
            $this->assign('classify', $classify);
            $this->assign('lang', $this->getDictionary('lang'));
            $this->assign('productInfo', $productInfo);
            $this->assign('category', $this->getCategory($company_id));
            return $this->fetch('productEdit');
        }
    }

    /**
     * 查看产品详情
     * @param $id
     * @param $lang
     * @return mixed
     */
    public function productInfo($id, $lang)
    {
        $company_id = iget('company_id') ? iget('company_id') : $this->company_id;
        $productInfo = $this->ProductModel->productInfo($id, $lang, $company_id);
        $this->assign('productInfo', $productInfo);
        return $this->fetch('productInfo');
    }

    /**
     * 新产品图片上传
     */
    public function uploade()
    {
        $dir = '/files/' . isession('user_id') . '/product/' . date("Ymd", time()) . "/";
        $res = $this->imgUploads($_FILES['imgs'], $dir, ['jpg', 'gif', 'png']);
        echo json_encode($res);
        exit;
    }

    /**
     * 产品id，语言删除指定产品信息
     */
    public function delete()
    {
        $this->ProductModel->productDel(post(), $this->company_id);
        $this->success('删除成功');
    }

    /**
     * 产品审核
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function audit()
    {
        $data = post();
        $where['audit'] = 1;
        if (checkArr($data['guid'])) {
            $where['guid'] = ['in', $data['guid']];
            $res = $this->ProductModel->updateAudit($where, $data['lang'], 2, $this->company_id);
            if ($res) {
                $this->success('审核成功');
            }
        } else {
            $where['guid'] = $data['guid'];
            $res = $this->ProductModel->updateAudit($where, $data['lang'], $data['audit'], $this->company_id);
            if ($res) {
                if ($data['audit'] == 2) {
                    $this->subZy($data['id'], $data['lang']);
                }
                $this->success('审核成功');
            }
        }
        $this->error('审核失败');
    }

    /**
     * 上传产品到智赢
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function updatezy()
    {
        $data = post();
        $res = $this->subZy($data['id'], $data['lang']);
        if ($res['status'] == false) {
            $this->error($res['msg']);
        }
        $this->success('上传成功');
    }

    /**
     * 提交数据到智赢
     * @param $id
     * @param $lang
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function subZy($id, $lang)
    {
        //获取用户token
        $user = DB::name('user')->where('id', isession('user_id'))->find();
        if (empty($user['token'])) {
            return ['status' => false, 'msg' => '当前用户token不存在'];
        }
        $productInfo = $this->ProductModel->productInfo($id, $lang, $this->company_id);
        //获取智赢分类
        $category = DB::name('bcategory')->where('id', $productInfo['bcate_id'])->find();
        if (!checkArr($category)) {
            return ['status' => false, 'msg' => '当前产品分类不存在'];
        }

        if (empty($category['zycategory'])) {
            return ['status' => false, 'msg' => '当前产品智赢分类不存在'];
        }

        $url = 'http://' . server('SERVER_NAME');
        $img = [];//总图片数组
        if (checkArr($productInfo['imgs'])) {
            foreach ($productInfo['imgs'] as $value) {
                $img[] = $url . $value['resource']['path'];
            }
        }

        $quantity = 0;
        $stock = [];
        if (checkArr($productInfo['shuxing'])) {
            $size = array(
                'Large' => 'L',
                'Medium' => 'M',
                'Small' => 'S',
                'X-Large' => 'XL',
                'X-Small' => 'XS',
                'XX-Large' => 'XXL',
                'XX-Small' => 'XXL',
                'XXX-Large' => 'XXXL',
                'XXX-Small' => 'XXXL',
                'XXXX-Large' => 'XXXXL',
                'XXXX-Small' => 'XXXXL',
                'XXXXX-Large' => 'XXXXL',
                'XXXXX-Small' => 'XXXXL'
            );
            $color = array('Beige' => 'Beige',
                'Black' => 'Black',
                'Blue' => 'Blue',
                'Bronze' => 'Bronze',
                'Brown' => 'Brown',
                'Gold' => 'Gold',
                'Green' => 'Green',
                'Grey' => 'Chrome',
                'Metallic' => 'Metallic',
                'Multicoloured' => 'Multi-colored',
                'Off-White' => 'Brass',
                'Orange' => 'Orange',
                'Pink' => 'Pink',
                'Purple' => 'Purple',
                'Red' => 'Red',
                'Silver' => 'Silver',
                'Transparent' => 'Clear',
                'Turquoise' => 'Bronze',
                'White' => 'White',
                'Yellow' => 'Yellow',
                'gray' => 'gray',
                'multicolored' => 'Multi-colored');
            if ($productInfo['btname'] == 'ColorSize') {
                $res = $this->doubleStock($productInfo['shuxing'], $size, $color, $url);
                $stock = $res['stock'];
                $quantity = $res['quantity'];
                $img = $img + $res['img'];
            } elseif ($productInfo['btname'] == 'Color') {
                foreach ($productInfo['shuxing'] as $key => $value) {
                    $bimg = [];
                    if (isset($value['imgs']) && count($value['imgs']) > 0) {

                        foreach ($value['imgs'] as $v) {
                            $img[] = $url . $v['path'];
                            $bimg[] = $url . $v['path'];
                        }
                    }
                    $quantity = $quantity + $value['kucun'];
                    $stock[] = array(
                        'color' => $value['cname'],
                        'size' => '',
                        'no' => $value['skucode'],
                        'num' => $value['kucun'],
                        'img' => implode(',', $bimg)
                    );
                }
            } else {//默认'Size'
                foreach ($productInfo['shuxing'] as $key => $value) {
                    $bimg = [];
                    if (isset($value['imgs']) && count($value['imgs']) > 0) {

                        foreach ($value['imgs'] as $v) {
                            $img[] = $url . $v['path'];
                            $bimg[] = $url . $v['path'];
                        }
                    }
                    $quantity = $quantity + $value['kucun'];
                    $stock[] = array(
                        'color' => '',
                        'size' => $value['cname'],
                        'no' => $value['skucode'],
                        'num' => $value['kucun'],
                        'img' => implode(',', $bimg)
                    );
                }
            }

        }
        $sales = array(
            'sku' => $productInfo['skucode'],
            'brand' => $productInfo['brand'],
            'kind' => $category['zycategory'],
            'title' => ['en' => $productInfo['proname']],
            'keys' => ['en' => $productInfo['keywords']],
            'bullet' => ['en' => $productInfo['content']],
            'intro' => ['en' => $productInfo['des']],
            'cur' => $productInfo['coin'],
            'price' => $productInfo['saleprice'],
            'cost' => $productInfo['cost'],
            'freight' => $productInfo['carriage'],
            'declare' => 0,
            'shipid' => 0,
            'quantity' => $productInfo['kucun'] + $quantity,
            'items' => 1,
            'weight' => $productInfo['weight'],
            'pic' => $img,
            'origin' => $productInfo['origin'],
            'facturer' => $productInfo['facturer'],
            'number' => $productInfo['number'],
            'department' => $productInfo['department'],
            'material' => $productInfo['material'],
            'metal' => $productInfo['metal'],
            'gem' => $productInfo['gem'],
            'package' => $productInfo['package'],
            'hscode' => $productInfo['hscode'],
            'english' => $productInfo['english'],
            'chinese' => $productInfo['chinese'],
            'source' => $productInfo['fromurl'],
            'memo' => ''
        );
        checkArr($stock) && $sales['stock'] = $stock;
        $data = array(
            'token' => $user['token'],
            'sales' => array($sales)
        );

        $con = request_post('http://api.zying.net/add.ashx', json_encode($data));
        $content = json_decode($con, true);
        if (isset($content['msg'])) {
            return ['status' => false, 'msg' => $content['msg']];
        }
        $this->ProductModel->updateProduct($id, ['iszy' => 2], $lang, $this->company_id);
        return ['status' => true];
    }

    /**
     * 双变体组装stock
     * @param array $shuxing
     * @param array $size
     * @param array $color
     * @param string $url
     * @return array
     */
    private function doubleStock($shuxing = [], $size = [], $color = [], $url = '')
    {
        $stock = [];
        $sx = [];
        $sxs = [];
        $quantity = 0;
        foreach ($shuxing as $key => $value) {
            $shuxing = [];
            if (strstr($value['cname'], ',')) {
                $arr = explode(',', $value['cname']);
                foreach ($arr as $v) {
                    if (isset($color[$v])) {
                        $shuxing['color'] = $color[$v];
                        $sxs['color'][] = $color[$v];
                    } elseif (isset($size[$v])) {
                        $shuxing['size'] = $size[$v];
                        $sxs['size'][] = $size[$v];
                    }
                }
            } else {
                if (isset($color[$value['cname']])) {
                    $shuxing['color'] = $color[$value['cname']];
                    $sxs['color'][] = $color[$value['cname']];
                } elseif (isset($size[$value['cname']])) {
                    $shuxing['size'] = $size[$value['cname']];
                    $sxs['size'][] = $size[$value['cname']];
                }
            }
            if (isset($shuxing['color']) || isset($shuxing['size'])) {
                $cshuxing = isset($shuxing['color']) ? $shuxing['color'] : '';
                $sshuxing = isset($shuxing['size']) ? $shuxing['size'] : '';
                $sx[] = $cshuxing . ',' . $sshuxing;
            }

            $shuxing['no'] = $value['skucode'];
            $shuxing['num'] = $value['kucun'];
            $quantity = $quantity + $value['kucun'];
            if (isset($value['imgs']) && count($value['imgs']) > 0) {
                $bimg = [];
                foreach ($value['imgs'] as $v) {
                    $img[] = $url . $v['path'];
                    $bimg[] = $url . $v['path'];
                }
                $shuxing['img'] = implode(',', $bimg);
            }
            $stock[] = $this->zySort($shuxing);
        }
        if (isset($sxs['size']) && checkArr($sxs['size'])) {
            $sizes = array_unique($sxs['size']);
            foreach ($sizes as $value) {
                if (isset($sxs['color']) && checkArr($sxs['color'])) {
                    $colors = array_unique($sxs['color']);
                    foreach ($colors as $v) {
                        $str = $v . ',' . $value;
                        if (!in_array($str, $sx)) {
                            $stock[] = array(
                                'color' => $v,
                                'size' => $value,
                                'no' => '',
                                'num' => 0,
                                'img' => ''
                            );
                        }
                    }
                }
            }
        }
        return ['stock' => $stock, 'quantity' => $quantity, 'img' => $img];
    }

    /**
     * 智赢数组排序
     * @param array $data
     * @return array
     */
    public function zySort($data = [])
    {
        return array(
            'color' => isset($data['color']) ? $data['color'] : '',
            'size' => isset($data['size']) ? $data['size'] : '',
            'no' => $data['no'],
            'num' => $data['num'],
            'img' => $data['img']
        );
    }

    /**
     * 一键翻译
     * @param $id
     * @param $lang
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function fanyi($id, $lang)
    {
        $productInfo = $this->ProductModel->productInfo($id, $lang, $this->company_id);
        if (post()) {
            $data = post();
            //未选择目标语言
            if (!isset($data['langs']) || count($data['langs']) == 0) {
                $this->error("请选择所需要翻译的目标语言！");
            }
            $htmlData = $productInfo['content'];
            $title = $productInfo['proname'];
            $sketch = $productInfo['sketch'];
            $keywords = $productInfo['keywords'];
            $session = getSession();
            foreach ($data['langs'] as $key => $vo) {
                $url = "http://translate.google.cn/translate_a/single?client=gtx&sl=auto&tl=" . $vo . "&dt=t&q=" . urlencode($title . "{@@@}" . $htmlData . "{@@@}" . $sketch . "{@@@}" . $keywords);
                $html = json_decode($this->gethtml($url));
                $tt = '';
                if (!isset($html[0]) || !checkArr($html[0])) {
                    $this->error('翻译太频繁，请稍后再试');
                }
                foreach ($html[0] as $value) {
                    (isset($value[0]) && !empty($value[0])) && $tt .= $value[0];
                }
                $thtml = explode("{@@@}", transitionbr($tt));

                //处理翻译后的数据
                if (checkArr($thtml)) {
                    $dataArr['proname'] = ucwords($thtml[0]);
                    $dataArr['content'] = $thtml[1];
                    $dataArr['sketch'] = $thtml[2];
                    $dataArr['keywords'] = $thtml[3];
                } else {
                    $dataArr['proname'] = $productInfo['proname'];
                    $dataArr['content'] = $productInfo['content'];
                    $dataArr['sketch'] = $productInfo['sketch'];
                    $dataArr['keywords'] = $productInfo['keywords'];
                    $err[] = $vo;
                }
                $this->ProductModel->productHandle($productInfo, $vo, $session, $dataArr, $lang);
            }
            $this->success('翻译成功');
        } else {
            //获取语言数据
            $this->assign('lang', $this->getDictionary('lang'));
            $this->assign('productInfo', $productInfo);
            return $this->fetch('productFanyi');
        }
    }

    /**
     * 抓取翻译页面数据
     * @param $url
     * @return bool|string
     */
    function gethtml($url)
    {
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_REFERER, "http://translate.google.cn/");
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36');
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        //执行命令
        if ($httpCode !== 200) {
            return "err";
        } else {
            return $data;
        }
        //关闭URL请求
        curl_close($curl);
    }

    /**
     * 去水印
     * @return mixed
     */
    public function imgtool()
    {
        if (isset($_FILES['Filedata'])) {

            if ($_FILES['Filedata']['error'] > 0) {
                return false;
            } else {
                $img_data = $_FILES['Filedata']['tmp_name'];
                $size = getimagesize($img_data);
                $file_type = $size['mime'];
                if (!in_array($file_type, array('image/jpg', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/gif'))) {
                    return false;
                }
            }
            //图片保存路径,默认保存在该代码所在目录(可根据实际需求修改保存路径)
            $save_path = get('path');
            $name = get('name');
            $filename = server('DOCUMENT_ROOT') . $save_path . '/' . $name;

            $result = move_uploaded_file($img_data, $filename);
            return $result ? '上传成功' : '保存失败';
        } else {
            $img = get('img');
            $msg = explode('/', $img);
            $i = count($msg);
            $name = $msg[$i - 1];
            unset($msg[$i - 1]);
            $path = implode('/', $msg);

            $url = "http://" . server('HTTP_HOST') . get('img');
            $this->assign('url', $url);
            $meituupload = "http://" . server('HTTP_HOST') . "/admin/product/imgtool.html?name=" . $name . "&path=" . $path;
            $this->assign('meituupload', $meituupload);
            return $this->fetch('imgtool');
        }

    }

    /**
     * 批量导入
     */
    public function import()
    {
        $tmp_name = $_FILES["file"]["tmp_name"];
        $name = $_FILES["file"]["name"];
        $nname = explode('.', $name);
        if (end($nname) !== "csv") {
            $this->error('导入文件格式不正确!');
        }

        $handle = fopen($tmp_name, 'r');
        $result = $this->input_csv($handle); // 解析csv

        $len_result = count($result);
        if ($len_result == 0) {
            $this->error('此文件中没有数据！');
        }

        $platform = post('platform');
        for ($i = 1; $i < $len_result; $i++) { //循环获取各字段值
            $logos = [];
            $proname = ucwords(iconv('gb2312', 'utf-8', $result[$i][0])); //中文转码
            $price = $result[$i][1];
            $coin = $result[$i][2];
            $content = iconv('gb2312', 'utf-8', $result[$i][3]);
            $skucode = $result[$i][4];
            $bname = $result[$i][5];
            $keywords = $result[$i][6];
            $des = $result[$i][7];
            $weight = $result[$i][8];
            $kucun = $result[$i][9];
            $logos[] = $result[$i][10];
            $logos[] = $result[$i][11];
            $logos[] = $result[$i][12];
            $logos[] = $result[$i][13];
            $logos[] = $result[$i][14];
            $logos[] = $result[$i][15];
            $logos[] = $result[$i][16];
            $logos[] = $result[$i][17];
            $logos[] = $result[$i][18];
            $logos[] = $result[$i][19];
            $logo = array_filter($logos);

            $sketch = $result[$i][20];
            $bt = $result[$i][21];
            $fromurl = $result[$i][22];
            $type = $result[$i][23];//parent主产品child变体

            if (empty($code)) {
                $code = date("YmdHis") . rand(100, 999);
            }

            if ($type == 'parent') {//主产品检测重复
                if ($this->ProductModel->checkMainProduct($skucode)) {
                    $this->repetition[] = $skucode;
                    continue;
                }
                if (!isset($this->guids[$skucode])) {
                    $this->guids[$skucode] = create_guid();
                }

                //检测分类是否存在
                $where['platform'] = $platform;
                $where['bname'] = $bname;
                $where['user_name'] = ssession('username');
                $where['company_id'] = $this->company_id;

                $res = Db::name('bcategory')
                    ->where($where)
                    ->find();
                if (!checkArr($res)) {
                    $data = $where;
                    $data['truename'] = ssession('truename');
                    Db::name('bcategory')->insert($data);
                }

                $this->serial = 0;
                //添加主产品
                $insertProduct['proname'] = $proname;
                $insertProduct['price'] = $price;
                $insertProduct['saleprice'] = $price;
                $insertProduct['skucode'] = $skucode;
                $insertProduct['coin'] = $coin;
                $insertProduct['code'] = $code;
                $insertProduct['content'] = $content;
                $insertProduct['ndate'] = date("Y-m-d", time());
                $insertProduct['bname'] = $bname;
                $insertProduct['user_name'] = ssession('username');
                $insertProduct['sketch'] = $des;
                $insertProduct['keywords'] = $keywords;
                $insertProduct['weight'] = $weight;
                $insertProduct['kucun'] = $kucun;
                $insertProduct['fromurl'] = $fromurl;
                $insertProduct['platform'] = $platform;
                $insertProduct['sketch'] = $sketch;
                $insertProduct['guid'] = $this->guids[$skucode];
                $insertProduct['source'] = 2;
                $insertProduct['audit'] = 1;
                $insertProduct['timestamp'] = time();
                $this->ProductModel->insertProduct($insertProduct);

                $productImg = [];
                if (checkArr($logo)) {
                    foreach ($logo as $key => $value) {
                        if (checkString($value)) {
                            $resource_id = $this->ProductModel->insertResourceByUrl($value);
                            $productImg[] = ['resource_id' => $resource_id, 'guid' => $this->guids[$skucode], 'serial' => 0, 'px' => $key, 'updatetime' => date("Y-m-d H:i:s", time())];
                        }
                    }
                    checkArr($productImg) && $this->ProductModel->insertImg($productImg, 'all');
                }
            }

            if ($type == 'child') {
                //变体产品重复
                if (in_array($skucode, $this->repetition)) {
                    continue;
                }

                $this->serial = $this->serial + 1;
                //添加变体
                $insertProperty['serial'] = $this->serial;
                $insertProperty['cname'] = $bt;
                $insertProperty['guid'] = $this->guids[$skucode];
                $insertProperty['price'] = $price;
                $insertProperty['saleprice'] = $price;
                $insertProperty['kucun'] = $kucun;
                $insertProperty['skucode'] = $skucode;
                $this->ProductModel->insertProperty($insertProperty);

                $propertyImg = [];
                if (checkArr($logo)) {
                    foreach ($logo as $key => $value) {
                        if (checkString($value)) {
                            $resource_id = $this->ProductModel->insertResourceByUrl($value);
                            $propertyImg[] = ['resource_id' => $resource_id, 'guid' => $this->guids[$skucode], 'serial' => 0, 'px' => $key, 'updatetime' => date("Y-m-d H:i:s", time())];
                        }
                    }
                    checkArr($propertyImg) && $this->ProductModel->insertImg($propertyImg, 'all');
                }
            }

        }
        fclose($handle); //关闭指针
        $this->success('全部导入成功!');
    }

    /**
     * 图片下载
     */
    public function uploadImg()
    {
        $filename = sget('filename');
        $path = server('DOCUMENT_ROOT');
        if (file_exists($path . $filename) == false) {
            $filename = "/public/static/images/noimg.png";
        }
        $filename = $path . $filename;
        //设置头信息
        header("Content-Type: application/force-download");
        header('Content-Disposition:attachment;filename=' . basename($filename));
        header('Content-Length:' . filesize($filename));
        //读取文件并写入到输出缓冲
        readfile($filename);
        exit();
    }

    /**
     * 下载文件
     */
    public function downloadFile()
    {
        $filename = server('DOCUMENT_ROOT') . sget('filename');
        //检测是否设置文件名和文件是否存在
        if ((isset($filename)) && (file_exists($filename))) {
            header("Content-length: " . filesize($filename));
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
            readfile("$filename");
        } else {
            echo "文件不存在!";
        }
    }

    /**
     * 检测产品重复
     */
    public function detectionRepeate()
    {
        $data = post();
        $res = $this->ProductModel->detectionRepeate($data, $this->company_id);
        if ($res['status'] == false) {
            $this->error($res['msg']);
        }
        $this->success($res['msg']);
    }

    /******************************* 批量导出 ********************************/

    /**
     * 导出excel
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function exportExcel()
    {
        if (!isset($_POST['types'])) {
            return $this->fetch('exportExcel');
        }
        //查找产品信息
        $product = $this->ProductModel->getProductList(post(), $this->company_id);
        $this->dir = server('SERVER_NAME');
//d($product);
        switch (ipost('types')) {
            case 1://导出亚马逊欧洲EAN表
                $this->exportAmazon($product);
                break;
        }
    }

    /**
     * 导出亚马逊欧洲EAN表
     * @param array $productList
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function exportAmazon($productList = [])
    {
        Loader::import('PHPXLSXWriter\xlsxwriter', EXTEND_PATH);
        $writer = new \XLSXWriter();
        //文件名
        $filename = "amazon" . date('Ymdhis', time()) . ".xlsx";
        header('Content-disposition: attachment; filename="' . \XLSXWriter::sanitize_filename($filename) . '"');
        header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        header('Content-Transfer-Encoding: binary');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        //工作簿名称
        $sheet1 = 'sheet1';
        //设置列格式，suppress_row: 去掉会多出一行数据；widths: 指定每列宽度
        $sheetHeader1 = [
            'TemplateType=fptcustom',
            'Version=2018.0727',
            'TemplateSignature=S0lUQ0hFTg==',
            'The top 3 rows are for Amazon.com use only. Do not',
            '',
            '',
            '',
            '',
            '',
            '',
            'Images',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            'Variation',
            '',
            '',
            '',
            'Basic',
            '',
            '',
            '',
            '',
            '',
            'Discovery',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            'Product Enrichment',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            'Dimensions',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            'Fulfillment',
            '',
            '',
            '',
            '',
            '',
            '',
            'Compliance',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            'Offer',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            'b2b',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            ''
        ];
        $sheetHeader2 = [
            'Product Type',
            'Seller SKU',
            'Brand Name',
            'Product Name',
            'Manufacturer',
            'Recommended Browse Nodes',
            'Standard Price',
            'Quantity',
            'Merchant Shipping Group',
            'Main Image URL',
            'Swatch Image URL',
            'Other Image Url',
            'Other Image Url',
            'Other Image Url',
            'Other Image Url',
            'Other Image Url',
            'Other Image Url',
            'Other Image Url',
            'Other Image Url',
            'Parentage',
            'Parent SKU',
            'Relationship Type',
            'Variation Theme',
            'Update Delete',
            'GTIN Exemption Reason',
            'Product ID',
            'Product ID Type',
            'Manufacturer Part Number',
            'Product Description',
            'Merchant Catalogue Number',
            'Key Product Features',
            'Key Product Features',
            'Key Product Features',
            'Key Product Features',
            'Key Product Features',
            'Search Terms',
            'Search Terms',
            'Search Terms',
            'Search Terms',
            'Search Terms',
            'Platinum Keyword',
            'Platinum Keyword',
            'Platinum Keyword',
            'Platinum Keyword',
            'Platinum Keyword',
            'Home & Furniture Target Audience',
            'size_map',
            'length_range',
            'width_range',
            'Scent',
            'Colour',
            'Color Map',
            'Size',
            'Material Type',
            'Item Width Unit Of Measure',
            'item_width',
            'item_height',
            'Item Height Unit Of Measure',
            'Item Dimensions Unit Of Measure',
            'Item Length Unit Of Measure',
            'item_length',
            'Display Depth',
            'Item Display Depth Unit Of Measure',
            'Shipping Weight',
            'Website Shipping Weight Unit Of Measure',
            'Vacuum Sealer Bag Length',
            'Item Display Length Unit Of Measure',
            'Display Width',
            'Item Display Width Unit Of Measure',
            'Display Height',
            'Item Display Height Unit Of Measure',
            'Display Diameter',
            'Item Display Diameter Unit Of Measure',
            'Vacuum & Floor Care Item Weight',
            'Item Display Weight Unit Of Measure',
            'Volume',
            'Volume Capacity Name Unit Of Measure',
            'Volume Capacity of the appliance',
            'Item Display Volume Unit Of Measure',
            'Package Weight Unit Of Measure',
            'Package Dimensions Unit Of Measure',
            'package_weight',
            'Package Length',
            'Package Width',
            'Package Height',
            'Fulfillment Centre ID',
            'specific_uses_for_product1',
            'specific_uses_for_product2',
            'specific_uses_for_product3',
            'specific_uses_for_product4',
            'specific_uses_for_product5',
            'Product fiche',
            'Energy efficiency label',
            'legal_disclaimer_description',
            'safety_warning',
            'fedas_id',
            'EU Toys Safety Directive Age-Specific Warning',
            'EU Toys Safety Directive Non-Age-Specific Warning',
            'EU Toys Safety Directive Language Warning',
            'Country/Region of declaration',
            'Batteries are Included',
            'Is this product a battery or does it utilise batte',
            'Battery type/size',
            'Battery type/size',
            'Battery type/size',
            'Number of batteries',
            'Number of batteries',
            'Number of batteries',
            'Battery composition',
            'Battery weight (grams)',
            'battery_weight_unit_of_measure',
            'Number of Lithium Metal Cells',
            'Number of Lithium-ion Cells',
            'Lithium Battery Packaging',
            'Watt hours per battery',
            'lithium_battery_energy_content_unit_of_measure',
            'Lithium content (grams)',
            'lithium_battery_weight_unit_of_measure',
            'Applicable Dangerous Goods Regulations',
            'Applicable Dangerous Goods Regulations',
            'Applicable Dangerous Goods Regulations',
            'Applicable Dangerous Goods Regulations',
            'Applicable Dangerous Goods Regulations',
            'UN number',
            'Safety Data Sheet (SDS) URL',
            'Item Weight',
            'item_weight_unit_of_measure',
            'Volume',
            'item_volume_unit_of_measure',
            'Flash point (°C)?',
            'Categorization/GHS pictograms (select all that app',
            'Categorization/GHS pictograms (select all that app',
            'Categorization/GHS pictograms (select all that app',
            'Recommended Retail Price',
            'weee_tax_value',
            'Number of Items',
            'weee_tax_value_unit_of_measure',
            'Stop Selling Date',
            'Max Order Quantity',
            'Offering Release Date',
            'Scheduled Delivery SKU List',
            'Launch Date',
            'Currency',
            'Package Quantity',
            'Product Tax Code',
            'Release Date',
            'Sale Price',
            'Sale From Date',
            'Sale End Date',
            'Item Condition',
            'Offer Condition Note',
            'Handling Time',
            'Restock Date',
            'Maximum Aggregate Ship Quantity',
            'Can Be Gift Messaged',
            'Is Gift Wrap Available?',
            'Is Discontinued by Manufacturer',
            'Registered Parameter',
            'Business Price',
            'Quantity Price Type',
            'Quantity Lower Bound 1',
            'Quantity Price 1',
            'Quantity Lower Bound 2',
            'Quantity Price 2',
            'Quantity Lower Bound 3',
            'Quantity Price 3',
            'Quantity Lower Bound 4',
            'Quantity Price 4',
            'Quantity Lower Bound 5',
            'Quantity Price 5',
            'National Stock Number',
            'United Nations Standard Products and Services Code',
            'Pricing Action'
        ];
        $sheetHeader3 = [
            'feed_product_type',
            'item_sku',
            'brand_name',
            'item_name',
            'manufacturer',
            'recommended_browse_nodes',
            'standard_price',
            'quantity',
            'merchant_shipping_group_name',
            'main_image_url',
            'swatch_image_url',
            'other_image_url1',
            'other_image_url2',
            'other_image_url3',
            'other_image_url4',
            'other_image_url5',
            'other_image_url6',
            'other_image_url7',
            'other_image_url8',
            'parent_child',
            'parent_sku',
            'relationship_type',
            'variation_theme',
            'update_delete',
            'gtin_exemption_reason',
            'external_product_id',
            'external_product_id_type',
            'part_number',
            'product_description',
            'catalog_number',
            'bullet_point1',
            'bullet_point2',
            'bullet_point3',
            'bullet_point4',
            'bullet_point5',
            'generic_keywords1',
            'generic_keywords2',
            'generic_keywords3',
            'generic_keywords4',
            'generic_keywords5',
            'platinum_keywords1',
            'platinum_keywords2',
            'platinum_keywords3',
            'platinum_keywords4',
            'platinum_keywords5',
            'target_audience_keywords',
            'size_map',
            'length_range',
            'width_range',
            'scent_name',
            'color_name',
            'color_map',
            'size_name',
            'material_type',
            'item_width_unit_of_measure',
            'item_width',
            'item_height',
            'item_height_unit_of_measure',
            'item_dimensions_unit_of_measure',
            'item_length_unit_of_measure',
            'item_length',
            'item_display_depth',
            'item_display_depth_unit_of_measure',
            'website_shipping_weight',
            'website_shipping_weight_unit_of_measure',
            'item_display_length',
            'item_display_length_unit_of_measure',
            'item_display_width',
            'item_display_width_unit_of_measure',
            'item_display_height',
            'item_display_height_unit_of_measure',
            'item_display_diameter',
            'item_display_diameter_unit_of_measure',
            'item_display_weight',
            'item_display_weight_unit_of_measure',
            'volume_capacity_name',
            'volume_capacity_name_unit_of_measure',
            'item_display_volume',
            'item_display_volume_unit_of_measure',
            'package_weight_unit_of_measure',
            'package_dimensions_unit_of_measure',
            'package_weight',
            'package_length',
            'package_width',
            'package_height',
            'fulfillment_center_id',
            'specific_uses_for_product1',
            'specific_uses_for_product2',
            'specific_uses_for_product3',
            'specific_uses_for_product4',
            'specific_uses_for_product5',
            'product_efficiency_image_url',
            'energy_efficiency_image_url',
            'legal_disclaimer_description',
            'safety_warning',
            'fedas_id',
            'eu_toys_safety_directive_age_warning',
            'eu_toys_safety_directive_warning',
            'eu_toys_safety_directive_language',
            'country_string',
            'are_batteries_included',
            'batteries_required',
            'battery_type1',
            'battery_type2',
            'battery_type3',
            'number_of_batteries1',
            'number_of_batteries2',
            'number_of_batteries3',
            'battery_cell_composition',
            'battery_weight',
            'battery_weight_unit_of_measure',
            'number_of_lithium_metal_cells',
            'number_of_lithium_ion_cells',
            'lithium_battery_packaging',
            'lithium_battery_energy_content',
            'lithium_battery_energy_content_unit_of_measure',
            'lithium_battery_weight',
            'lithium_battery_weight_unit_of_measure',
            'supplier_declared_dg_hz_regulation1',
            'supplier_declared_dg_hz_regulation2',
            'supplier_declared_dg_hz_regulation3',
            'supplier_declared_dg_hz_regulation4',
            'supplier_declared_dg_hz_regulation5',
            'united_nations_regulatory_id',
            'safety_data_sheet_url',
            'item_weight',
            'item_weight_unit_of_measure',
            'item_volume',
            'item_volume_unit_of_measure',
            'flash_point',
            'ghs_classification_class1',
            'ghs_classification_class2',
            'ghs_classification_class3',
            'list_price',
            'weee_tax_value',
            'number_of_items',
            'weee_tax_value_unit_of_measure',
            'offering_end_date',
            'max_order_quantity',
            'offering_start_date',
            'delivery_schedule_group_id',
            'product_site_launch_date',
            'currency',
            'item_package_quantity',
            'product_tax_code',
            'merchant_release_date',
            'sale_price',
            'sale_from_date',
            'sale_end_date',
            'condition_type',
            'condition_note',
            'fulfillment_latency',
            'restock_date',
            'max_aggregate_ship_quantity',
            'offering_can_be_gift_messaged',
            'offering_can_be_giftwrapped',
            'is_discontinued_by_manufacturer',
            'missing_keyset_reason',
            'business_price',
            'quantity_price_type',
            'quantity_lower_bound1',
            'quantity_price1',
            'quantity_lower_bound2',
            'quantity_price2',
            'quantity_lower_bound3',
            'quantity_price3',
            'quantity_lower_bound4',
            'quantity_price4',
            'quantity_lower_bound5',
            'quantity_price5',
            'national_stock_number',
            'unspsc_code',
            'pricing_action'
        ];
        $styles2 = array('font' => '宋体', 'font-style' => 'bold', 'border' => 'left,right,top,bottom');
        $writer->writeSheetRow($sheet1, $sheetHeader1, $styles2);
        $writer->writeSheetRow($sheet1, $sheetHeader2, $styles2);
        $writer->writeSheetRow($sheet1, $sheetHeader3, $styles2);

        if (checkArr($productList)) {
            $brand = post("brand");
            $productType = post("productType");
            $manufacturer = post("manufacturer");
            $recommended = post("recommended");
            foreach ($productList as $value) {
                $key1 = "";
                $key2 = "";
                $key3 = "";
                $key4 = "";
                $key5 = "";
                $des1 = "";
                $des2 = "";
                $des3 = "";
                $des4 = "";
                $des5 = "";
                if (checkArr($value)) {
                    $imgList = $this->ProductModel->getOneProductImg($value['guid'], post('lang'), 0, $this->company_id);
                    $img1 = isset($imgList[0]['path']) ? $this->trueUrl($imgList[0]['path']) : '';
                    $img2 = isset($imgList[1]['path']) ? $this->trueUrl($imgList[1]['path']) : '';
                    $img3 = isset($imgList[2]['path']) ? $this->trueUrl($imgList[2]['path']) : '';
                    $img4 = isset($imgList[3]['path']) ? $this->trueUrl($imgList[3]['path']) : '';
                    $img5 = isset($imgList[4]['path']) ? $this->trueUrl($imgList[4]['path']) : '';
                    $img6 = isset($imgList[5]['path']) ? $this->trueUrl($imgList[5]['path']) : '';
                    $img7 = isset($imgList[6]['path']) ? $this->trueUrl($imgList[6]['path']) : '';
                    $img8 = isset($imgList[7]['path']) ? $this->trueUrl($imgList[7]['path']) : '';
                    $img9 = isset($imgList[8]['path']) ? $this->trueUrl($imgList[8]['path']) : '';

                    $spliter = "<br/>";
                    if (!empty($value['keywords'])) {
                        $keywords = transitionbr($value["keywords"], $spliter);
                        $keys = explode($spliter, $keywords);
                        if (checkArr($keys)) {
                            $m = 0;
                            foreach ($keys as $w) {
                                $w = trim($w);
                                if (!empty($w)) {
                                    $key[$m] = $w;
                                    $m++;
                                }
                            }
                        }
                        isset($key[0]) && $key1 = $key[0];
                        isset($key[1]) && $key2 = $key[1];
                        isset($key[2]) && $key3 = $key[2];
                        isset($key[3]) && $key4 = $key[3];
                        isset($key[4]) && $key5 = $key[4];
                    }


                    $content = transitionbr($value["content"], $spliter);
                    $sketch = transitionbr($value["sketch"], $spliter);
                    ipost('des') == 1 && $content = $this->handContent($content, $brand, $imgList);
                    //卖点拆分
                    $deses = explode($spliter, $sketch);
                    if (checkArr($deses)) {
                        $m = 0;
                        $des = [];
                        foreach ($deses as $w) {
                            $w = trim($w);
                            if (!empty($w)) {
                                $des[$m] = $w;
                                $m++;
                            }
                        }
                        isset($des[0]) && $des1 = $des[0];
                        isset($des[1]) && $des2 = $des[1];
                        isset($des[2]) && $des3 = $des[2];
                        isset($des[3]) && $des4 = $des[3];
                        isset($des[4]) && $des5 = $des[4];
                    }
                    $sku = $value["skucode"];

                    //变体
                    $shuxingList = $this->ProductModel->getPriductShuxing($value['guid'], post('lang'), $this->company_id);
                    if (!checkArr($shuxingList)) {
                        $ean = $this->EAN13(randomkeys(12));
                        $tbody = [
                            $productType,
                            $sku,
                            $brand,
                            $this->truncation($value["proname"], 200),
                            $manufacturer,
                            $recommended,
                            $value["saleprice"],
                            $value["kucun"],
                            'Migrated Template',
                            $img1,
                            $img1,
                            $img2,
                            $img3,
                            $img4,
                            $img5,
                            $img6,
                            $img7,
                            $img8,
                            $img9,
                            '',
                            '',
                            '',
                            $value["btname"],
                            'update',
                            '',
                            $ean,
                            'EAN',
                            '',
                            $content,
                            '',
                            $des1,
                            $des2,
                            $des3,
                            $des4,
                            $des5,
                            $key1,
                            $key2,
                            $key3,
                            $key4,
                            $key5,
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            'New',
                            '',
                            '10',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            ''
                        ];
                        $writer->writeSheetRow($sheet1, $tbody);
                    } else {
                        $tbody = [
                            $productType,
                            $sku,
                            $brand,
                            $this->truncation($value["proname"], 200),
                            $manufacturer,
                            $recommended,
                            $value["saleprice"],
                            $value["kucun"],
                            'Migrated Template',
                            $img1,
                            $img1,
                            $img2,
                            $img3,
                            $img4,
                            $img5,
                            $img6,
                            $img7,
                            $img8,
                            $img9,
                            'parent',
                            '',
                            '',
                            $value["btname"],
                            'update',
                            '',
                            '',
                            '',
                            '',
                            $content,
                            '',
                            $des1,
                            $des2,
                            $des3,
                            $des4,
                            $des5,
                            $key1,
                            $key2,
                            $key3,
                            $key4,
                            $key5,
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            'New',
                            '',
                            '10',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            ''
                        ];
                        $writer->writeSheetRow($sheet1, $tbody);
                        $i = 0;
                        $platform = 'Amazon';
                        $this->getPlatformContrast($platform);
                        foreach ($shuxingList as $v) {
                            $btimg = [];
                            $i = $i + 1;
                            $imgList = $this->ProductModel->getOneProductImg($value['guid'], post('lang'), $v['serial'], $this->company_id);
                            if (checkArr($imgList)) {
                                $m = 0;
                                foreach ($imgList as $w) {
                                    $m++;
                                    $btimg[$m] = $this->trueUrl($w['path']);
                                }
                            }

                            if (strpos($v["cname"], ",") !== false) {
                                $cname = explode(",", $v["cname"]);
                                $bsize = $this->getContrastShuxing(end($cname), $platform);
                                array_pop($cname);
                                $bcolor = $this->getContrastShuxing(join(',', $cname), $platform);
                            } else {
                                if ($value['btname'] == 'Color') {
                                    $bcolor = $this->getContrastShuxing($v["cname"], $platform);
                                    $bsize = "";
                                } else {
                                    $bcolor = '';
                                    $bsize = $this->getContrastShuxing($v["cname"], $platform);
                                }
                            }
                            $ean = $this->EAN13(randomkeys(12));
                            $tbody = [
                                $productType,
                                $sku . '-' . $i,
                                $brand,
                                $this->truncation($value["proname"] . "," . $v["cname"], 200),
                                $manufacturer,
                                $recommended,
                                $v["saleprice"],
                                $v["kucun"],
                                'Migrated Template',
                                isset($btimg[1]) ? $btimg[1] : '',
                                isset($btimg[1]) ? $btimg[1] : '',
                                isset($btimg[2]) ? $btimg[2] : '',
                                isset($btimg[3]) ? $btimg[3] : '',
                                isset($btimg[4]) ? $btimg[4] : '',
                                isset($btimg[5]) ? $btimg[5] : '',
                                isset($btimg[6]) ? $btimg[6] : '',
                                isset($btimg[7]) ? $btimg[7] : '',
                                isset($btimg[8]) ? $btimg[8] : '',
                                isset($btimg[9]) ? $btimg[9] : '',
                                'child',
                                $sku,
                                'Variation',
                                $value["btname"],
                                'update',
                                '',
                                $ean,
                                'EAN',
                                '',
                                $content,
                                '',
                                $des1,
                                $des2,
                                $des3,
                                $des4,
                                $des5,
                                $key1,
                                $key2,
                                $key3,
                                $key4,
                                $key5,
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                $bsize,
                                '',
                                '',
                                '',
                                $bcolor,
                                $bcolor,
                                $bsize,
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                'New',
                                '',
                                '10',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                ''
                            ];
                            $writer->writeSheetRow($sheet1, $tbody);
                        }
                    }
                }
            }
        }

        //合并单元格
        $writer->markMergedCell($sheet1, $start_row = 0, $start_col = 3, $end_row = 0, $end_col = 9);
        $writer->markMergedCell($sheet1, $start_row = 0, $start_col = 10, $end_row = 0, $end_col = 18);
        $writer->markMergedCell($sheet1, $start_row = 0, $start_col = 19, $end_row = 0, $end_col = 22);
        $writer->markMergedCell($sheet1, $start_row = 0, $start_col = 23, $end_row = 0, $end_col = 28);
        $writer->markMergedCell($sheet1, $start_row = 0, $start_col = 29, $end_row = 0, $end_col = 45);
        $writer->markMergedCell($sheet1, $start_row = 0, $start_col = 46, $end_row = 0, $end_col = 53);
        $writer->markMergedCell($sheet1, $start_row = 0, $start_col = 54, $end_row = 0, $end_col = 78);
        $writer->markMergedCell($sheet1, $start_row = 0, $start_col = 79, $end_row = 0, $end_col = 85);
        $writer->markMergedCell($sheet1, $start_row = 0, $start_col = 86, $end_row = 0, $end_col = 132);
        $writer->markMergedCell($sheet1, $start_row = 0, $start_col = 133, $end_row = 0, $end_col = 157);
        $writer->markMergedCell($sheet1, $start_row = 0, $start_col = 158, $end_row = 0, $end_col = 172);

        $writer->writeToStdOut();
        exit(0);
    }

    /**
     * 获取平台所属变体属性对应信息
     * @param string $name
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getPlatformContrast($name = '')
    {
        //存在对应关系，或平台为空
        if ($name == '' || isset($this->platform_contrast[$name])) {
            return false;
        }
        //查询平台id
        $platform = DB::name('platform')->field('id')->where('english', $name)->find();
        if (!checkArr($platform)) {
            return false;
        }

        //查询属性对照信息
        $where['platform_id'] = $platform['id'];
        $where['company_id'] = $this->company_id;
        $contrast = DB::name('platform_contrast')->field('shuxing,property')->where($where)->select();
        checkArr($contrast) && $this->platform_contrast[$name] = arrayCombine($contrast, 'shuxing');
        return true;
    }

    /**
     * 返回对应信息
     * @param string $shuxing
     * @param string $platform
     * @return string
     */
    private function getContrastShuxing($shuxing = '', $platform = '')
    {
        //对应信息为空，传过来属性为空，原样返回
        if (!isset($this->platform_contrast[$platform]) || count($this->platform_contrast[$platform]) == 0 || $shuxing == '' || $platform == '') {
            return $shuxing;
        }

        //存在对应信息，返回对应信息
        $small = strtolower($shuxing);
        if (isset($this->platform_contrast[$platform][$small])) {
            return $this->platform_contrast[$platform][$small]['property'];
        }
        return $shuxing;
    }

    /**
     * 处理描述追加主图
     * @param string $content
     * @param string $brand
     * @param array $imgList
     * @return mixed|string|string[]|null
     */
    private function handContent($content = '', $brand = '', $imgList = [])
    {
        if ($content == '') {
            $con = '';
        } else {
            $con = $this->replacebd($content, $brand);
        }

        if (ipost('des') == 1 && checkArr($imgList)) {
            foreach ($imgList as $value) {
                $img[] = "<img src='" . $this->trueUrl($value['path']) . "'>";
            }
            $con = $con == '' ? join('<br>', $img) : $con . '<br>' . join('<br>', $img);
        }
        return $con;
    }

    /**
     * 获取可直接访问图片地址
     * @param string $url
     * @return string
     */
    private function trueUrl($url = '')
    {
        if (strstr($url, 'http://') == false && strstr($url, 'https://') == false) {
            $url = "http://" . $this->dir . $url;
        }
        return $url;
    }

    /**
     * 超过长度
     * @param string $str
     * @param string $num
     * @return string
     */
    private function truncation($str = '', $num = '')
    {
        if ($num == '') {
            return $str;
        }
        if ($num > 3 && mb_strlen($str) > $num) {
            $str = mb_substr($str, 0, $num - 3);
            $str .= '...';
        } elseif (mb_strlen($str) > $num) {
            $str = mb_substr($str, 0, $num);
        }
        return $str;
    }

    private function replacebd($str1, $str2)
    {
        $s1 = explode("Brand Name:", $str1);
        $s11 = isset($s1[1]) ? $s1[1] : '';
        $s2 = explode('&lt;br/&gt;', $s11);
        $s21 = isset($s2[0]) ? $s2[0] : '';
        $s3 = str_replace($s21, $str2, $str1);
        return $s3;
    }

    private function EAN13($n)
    {
        $n = (string)$n;
        $a = (($n[1] + $n[3] + $n[5] + $n[7] + $n[9] + $n[11]) * 3 + $n[0] + $n[2] + $n[4] + $n[6] + $n[8] + $n[10]) % 10;
        $a = $a == 0 ? 0 : 10 - $a;
        return $n . $a;
    }

    /******************************* 分享 ********************************/

    /**
     * 一键分享
     */
    public function productShare()
    {
        $res = $this->ProductModel->insertShare(post(), $this->company_id);
        if ($res['status'] == false) {
            $this->error($res['msg']);
        }
        $this->success($res['msg']);
    }

    /**
     * 分享列表
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function productListShare()
    {
        $data = get();

        $proname = isset($data['proname']) ? $data['proname'] : '';
        $code = isset($data['code']) ? $data['code'] : '';
        $platform = isset($data['platform']) ? $data['platform'] : '';
        $share = isset($data['share']) ? $data['share'] : '';

        $where = !empty($code) ? "(code LIKE '%" . $data['code'] . "%' or skucode LIKE '%" . $code . "%')" : '';
        $where .= !empty($proname) ? $where ? " AND proname LIKE '%" . $proname . "%'" : "proname LIKE '%" . $proname . "%'" : '';
        $where .= !empty($platform) ? $where ? " AND platform = '" . $platform . "'" : " platform = '" . $platform . "'" : "";
        $where .= !empty($share) ? $where ? " AND share = '" . $share . "'" : " share = '" . $share . "'" : "";

        if ($share == 1) {
            $where .= $where ? " AND company_id = '" . $this->company_id . "'" : " company_id = '" . $this->company_id . "'";
        }
        $product = Db::name('products_share')
            ->where($where)
            ->order('id desc')
            ->paginate(12, false, ['query' =>
                [
                    'proname' => $proname,
                    'code' => $code,
                    'platformStr' => $platform,
                    'share' => $share
                ]]);

        $list = $product->all();
        $resources = [];
        if (checkArr($list)) {
            $ids = array_column($list, 'id');
            $iwhere['pid'] = ['in', join(',', $ids)];
            $iwhere['serial'] = 0;
            //获取图片关联数据
            $sql = Db::table('ean_img_share')
                ->where($iwhere)
                ->order('px asc')
                ->buildSql();

            $imgInfo = Db::table($sql . 'a')->group('a.pid')->select();
            if (checkArr($imgInfo)) {
                //获取资源id
                $resource_ids = array_column($imgInfo, 'resource_id');
                $resource = Db::name('resource_share')
                    ->where(['id' => ['in', join(',', $resource_ids)]])
                    ->select();
                checkArr($resource) && $resources = arrayCombine($resource, 'pid');
            }
        }
        //获取平台数据
        $platform = $this->getDictionary('platform');

        $this->assign('platform', $platform);
        $this->assign('product', $product);
        $this->assign('resources', $resources);
        return $this->fetch('productListShare');
    }

    /**
     * 删除分享产品
     * @param $id
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function deleteShare($id)
    {
        Db::name('products_share')->where('id', $id)->delete();
        Db::name('shuxing_share')->where('pid', $id)->delete();
        Db::name('img_share')->where('pid', $id)->delete();
        Db::name('resource_share')->where('pid', $id)->delete();
        $this->success("删除成功");
    }

    /**
     * 查看分享产品详情
     * @param $id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function productShareInfo($id)
    {
        //获取主产品信息
        $product = DB::name('products_share')->where('id', $id)->find();
        if (!checkArr($product)) {
            $this->error('当前分享产品不存在');
        }
        //获取变体信息
        $shuxing = DB::name('shuxing_share')->where('pid', $id)->order('serial asc')->select();
        checkArr($shuxing) && $shuxing = arrayCombine($shuxing, 'serial');
        //获取资源信息
        $resource = DB::name('resource_share')->where('pid', $id)->select();
        checkArr($resource) && $resource = arrayCombine($resource, 'id');

        //获取图片信息
        $img = DB::name('img_share')->where('pid', $id)->select();

        if (checkArr($img)) {
            foreach ($img as $value) {
                if ($value['serial'] == 0) {
                    isset($resource[$value['resource_id']]) && $product['imgs'][] = $resource[$value['resource_id']]['path'];
                }
                if ($value['serial'] > 0 && isset($shuxing[$value['serial']])) {
                    isset($resource[$value['resource_id']]) && $shuxing[$value['serial']]['imgs'][] = $resource[$value['resource_id']]['path'];
                }
            }
        }

        $this->assign('product', $product);
        $this->assign('shuxing', $shuxing);
        return $this->fetch('productShareInfo');
    }

    /**
     * 导入产品到个人产品库
     */
    public function uploadShare()
    {
        $id = ipost('id');
        $res = $this->ProductModel->uploadShareToOwn($id, $this->company_id);
        if ($res['status'] == false) {
            $this->error($res['msg']);
        }
        $this->success($res['msg']);
    }

    /**************************************** 违禁词管理 **************************************************/
    /**
     * 违禁词列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function illegalWords()
    {
        $where = [];
        get('words') && $where['words'] = ['like', '%' . sget('words') . '%'];
        //分页展示数据
        $data = Db::name('illegal_words')
            ->where($where)
            ->order('id asc')
            ->paginate(15, false, ['query' => [
                'words' => sget('words')
            ]]);
        $this->assign('data', $data);
        return $this->fetch('illegalWords');
    }

    /**
     * 添加违禁词
     * @return mixed
     */
    public function illegalWordsAdd()
    {
        if (post()) {
            $content = spost('words');
            $uid = isession('user_id');
            if (strpos($content, ',') !== false) {
                $contents = explode(',', $content);
                foreach ($contents as $value) {
                    checkString($value) && $insertArr[] = array(
                        'words' => $value,
                        'timestamp' => time()
                    );
                }
                Db::name('illegal_words')->insertAll($insertArr, 'IGNORE');
            } else {
                $data['words'] = $content;
                $data['timestamp'] = time();
                Db::name('illegal_words')->insert($data, 'IGNORE');
            }
            $this->success('添加成功');
        } else {
            return $this->fetch('illegalWordsAdd');
        }
    }

    /**
     * 删除违禁词
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function illegalWordsDel()
    {
        $data = post();
        if (checkArr($data['id'])) {
            $where['id'] = ['in', $data['id']];
        } else {
            $where['id'] = $data['id'];
        }
        Db::name('illegal_words')->where($where)->delete();
        $this->success("删除成功");
    }

    /**************************************** 批量产品改价 **************************************************/

    /**
     * 批量修改产品属性
     * @return mixed
     */
    public function changePrice()
    {
        if (!post()) {
            return $this->fetch('changePrice');
        }

        $res = $this->ProductModel->changePrice(post(), $this->company_id);
        if ($res['status'] == true) {
            $this->success($res['msg']);
        }
        $this->error($res['msg']);
    }

    /**
     * 批量同步产品变体信息
     * @return mixed
     */
    public function synchPrice(){
        if (!post()) {
            return $this->fetch('synchPrice');
        }

        $res = $this->ProductModel->synchPrice(post(), $this->company_id);
        if ($res['status'] == true) {
            $this->success($res['msg']);
        }
        $this->error($res['msg']);
    }

    /**************************************** 批量处理数据库 **************************************************/
    /**
     * 批量处理数据库表结构
     */
    public function batchTables()
    {
        //添加修改主产品表字段
        $this->ProductModel->batchProductsTable();
        //添加修改变体表字段
//        $this->ProductModel->batchShuxingTable();
    }

}